package http.bio;

import http.HttpRequest;
import http.HttpResponse;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * @author fengbo
 * @date 2018/10/21
 */
public class HttpTask implements Runnable {

    private final Socket socket;

    public HttpTask(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {

        InputStream input = null;
        OutputStream output = null;
        try {
            input = socket.getInputStream();
            output = socket.getOutputStream();

            HttpRequest request = new HttpRequest(input);
System.out.println("connect " + request.getHost() + "; read " + request.getUrl());
            HttpResponse response = new HttpResponse(request.getUrl());

            write(output, response.getHeader(), response.getBody());

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (input != null) {
                    input.close();
                }
                if (output != null) {
                    output.close();
                }
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    private void write(OutputStream output, String header, byte[] body) {
        try {
            output.write(header.getBytes());
            output.write(body);
            output.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
